package com.example.petplanet.service;



import com.alibaba.fastjson2.JSON;
import com.example.petplanet.domain.Message;
import com.example.petplanet.mapper.OfflineMessageDao;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
public class OfflineMessageService {



    private final OfflineMessageDao offlineMessageDao;

    public OfflineMessageService(OfflineMessageDao offlineMessageDao) {
        this.offlineMessageDao = offlineMessageDao;
    }

    //删除离线消息
    public void deleteMessage(long id) {
        offlineMessageDao.deleteById(id);
    }

    //添加离线消息
    public void addOfflineMessage(Message message,long fromUserId) {
        message.setSystem(false);
        message.setFromUserId(fromUserId);
        message.setCreatedAt(LocalDateTime.now());
        System.out.println(message);
        offlineMessageDao.insert(message);
    }

    //接受者的userId进行筛选
    public List<Message> getMessagesByUserId(long userId) {
        List<Message> offlineMessages = offlineMessageDao.selectMessageByUserId(userId);
        // 根据createdAt字段对消息进行排序，时间更早的排在前面
        Collections.sort(offlineMessages, Comparator.comparing(Message::getCreatedAt));
        return offlineMessages;
    }
}
